<template>
    <div class="height-full">
        <router-link to="/" custom v-slot="{ navigate }">
        <div class="fit-height rp">
            <div class="error404 tc">
                <p class="f40">404 error.</p>
                <p class="f16 mt10">找不到请求的页面</p>
                <p class="mt10 gray-1 f12">{{displayTime}}秒后将跳转至主页</p>
            </div>
            
            <span class="f18 btnText" @click="navigate">立即跳转</span>
        </div>
        </router-link>
    </div>
</template>
<script>
import { onBeforeUnmount, ref } from 'vue'
import { useRouter } from 'vue-router'

const countDown = function (t, opt) {
  const format = opt.format || 'dd HH:mm:ss'
  var f = function (m) {
    return m < 10 ? '0' + m : m
  }
  function a () {
    t = Math.max(t - 1, 0)
    if(t <= 0){
      clearInterval(interval)
      typeof opt.finished === 'function' && opt.finished()
    }
    let str = format
    str = str.replace('dd', f(Math.floor(t / (60*60*24))))
    str = str.replace('HH', f(Math.floor(t / (60*60))))
    str = str.replace('mm', f(Math.floor(t / 60)))
    str = str.replace('ss', f(Math.floor(t % 60)))
    if (typeof opt.callback === 'function') {
      opt.callback(str)
    }
  }
  a()
  let interval = setInterval(a, 1000)
  return interval
}

export default {
    setup(){
        const router = useRouter()
        const displayTime = ref('')
        const timer = countDown(5, {
            format:'ss',
            callback(time){
                displayTime.value = time||''
            },
            finished(){
                router.replace('/')
            }
        })

        onBeforeUnmount(()=>{
            timer && clearInterval(timer)
        })
        return {
            displayTime
        }
    }
}
</script>
<style lang="less" scoped>
.height-full{
  height: 100vh;
  background: #fff;
}
.error404 {
    position: absolute;
    left: 0;
    right: 0;
    top: 30%;
}
.btnText {
    position: absolute;
    cursor: pointer;
    left: 0;
    right: 0;
    bottom: 0.8rem;
    text-align: center;
}
</style>